package com.rlz.framemm;


import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.rlz.base.cache.CacheManager;
import com.rlz.base.tools.rxbus.RxBus;
import com.rlz.framemm.jni.MethodJni;
import com.rlz.framemm.mode.chain.OneCheck;
import com.rlz.framemm.mode.chain.ThreeCheck;
import com.rlz.framemm.mode.chain.TwoCheck;
import com.rlz.framemm.mode.decorator.cake.BigCake;
import com.rlz.framemm.mode.decorator.cake.Cake;
import com.rlz.framemm.mode.decorator.cake.CandleCake;
import com.rlz.framemm.mode.decorator.cake.CreamCake;
import com.rlz.framemm.mode.decorator.role.BlackPants;
import com.rlz.framemm.mode.decorator.role.GreenHair;
import com.rlz.framemm.mode.decorator.role.Hunter;
import com.rlz.framemm.mode.decorator.role.Master;
import com.rlz.framemm.mode.decorator.role.RedHair;
import com.rlz.framemm.mode.decorator.role.RedJacket;
import com.rlz.framemm.mode.decorator.role.WhiteJacket;
import com.rlz.framemm.mode.decorator.role.WhitePants;
import com.rlz.framemm.mode.observer.DingServer;
import com.rlz.framemm.mode.observer.User;
import com.rlz.framemm.mode.prototype.Message;
import com.rlz.framemm.mode.strategy.AirStrategy;
import com.rlz.framemm.mode.strategy.PersonStrategy;
import com.rlz.framemm.mode.strategy.TripContext;
import com.rlz.framemm.mode.strategy2.Discount;
import com.rlz.framemm.mode.strategy2.MovieTicket;
import com.rlz.framemm.mode.strategy2.XmlUtil;
import com.rlz.framemm.ui.BehaviorActivity;
import com.rlz.framemm.ui.BelowActivity;
import com.rlz.framemm.ui.LoginActivity;
import com.rlz.framemm.ui.TestActivity;
import com.rlz.framemm.ui.Web1Activity;
import com.rlz.framemm.util.GifPlayer;
import com.rlz.framemm.util.JniUtil;
import com.rlz.framemm.util.MD5;
import com.rlz.framemm.util.NightManager;
import com.youth.banner.BannerConfig;
import com.rlz.aspectj.AppInterceptor;
import com.rlz.aspectj.annotation.Intercept;
import com.rlz.aspectj.annotation.Permission;
import com.rlz.aspectj.annotation.SingleClick;
import com.rlz.aspectj.util.PermissionUtils;
import com.rlz.base.base.BaseActivity;
import com.rlz.base.util.ApkUtils;
import com.rlz.base.util.ThreadUtil;
import com.rlz.base.util.download.DownloadStatus;
import com.rlz.base.weiget.ProgressDialog;
import com.rlz.framemm.algorithm.MinStack;
import com.rlz.framemm.algorithm.Node;
import com.rlz.framemm.algorithm.Test;
import com.rlz.framemm.bean.BannerBean;
import com.rlz.framemm.databinding.ActivityMainBinding;
import com.rlz.framemm.model.HomeModel;
import com.rlz.framemm.proxy.ApiBookInterface;
import com.rlz.framemm.proxy.TestRetrofit;
import com.rlz.framemm.util.GlideImagesLoader;
import com.rlz.framemm.util.single.TestSingle;
import com.rlz.framemm.viewmodel.HomeViewModel;
import com.rlz.libs.log.P;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import io.reactivex.disposables.Disposable;

import static android.content.pm.PackageManager.GET_SIGNATURES;
import static com.bumptech.glide.request.target.Target.SIZE_ORIGINAL;
import static com.rlz.framemm.util.GifPlayer.T;


public class MainActivity extends BaseActivity<HomeModel, HomeViewModel, ActivityMainBinding> implements View.OnClickListener, PermissionUtils.OnPermissionDeniedListener {


    private List<String> mUrls;
    private List<String> mTitles;
    private static final int code = 1;
    private int mCount = 0;
    private ProgressDialog mDialog;
    private MinStack<Integer> mStack;
    private MethodJni mJni;
    private GifPlayer mPlayer;


    @Override
    public int layoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void logic() {
        /*try {
            mBinding.version.setText(getPackageManager().getPackageInfo(getPackageName(), 0).versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }*/
        mBinding.setOnClickListener(this);
        mBinding.mBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE);
        mBinding.mBanner.setImageLoader(new GlideImagesLoader());

        mViewModel.getBanners().observe(this, listResource -> {
            listResource.handler(new OnCallback<List<BannerBean>>() {
                @Override
                public void onSuccess(List<BannerBean> data) {
                    updateBanners(data);
                }
            });
        });

        /*NetWorkLiveData.Companion.getInstance().observe(this,
                isHaveNet -> Toast(isHaveNet ? "有" : "没有"));*/
        mStack = new MinStack<>();
        mStack.push(52);
        mStack.push(786);
        mStack.push(46);
        mStack.push(56);
        mStack.push(16);
        mStack.push(999);

        try {
            Runtime.getRuntime().exec("setprop log 0");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @SingleClick(3000) //参数为 防止连续点击的时间
    public void oncLickNew(View view) {
        mCount++;
        toast("点击了一次 ->" + mCount);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    protected void click() {
        super.click();
        mBinding.mBanner.setOnBannerListener(position -> {
            if (mUrls.isEmpty()) return;
            to(TestActivity.class);
        });

        mBinding.downLoad.setOnClickListener(v -> {
            //checkClick();
            //down();
            //oncLickNew(v);
            //setDrawable();
            //exchange();
            //mBinding.result.setText(mStack.getMin() +"");
            //log();
            //executeProxy();
            //single();
            //to(TestActivity.class);
            //chain();
            //observer();
            //strategy();
            //strategy2();

            //rxBus();
            //night();
            //decorator();
            //decorator2();
            //numberTest();
            //shareNetImage(this,"https://img2.baidu.com/it/u=1945464906,1635022113&fm=26&fmt=auto");

            //to(BehaviorActivity.class);
            //jni();
            //prototype();
            //blur();
            //md5();
            //gif();
            ams();
        });
        AppInterceptor.setOnPermissionDeniedListener(this);

        mBinding.result.setOnClickListener(v -> {
            CacheManager.Companion.getManager().clearUser();
        });

        mBinding.pause.setOnClickListener(v -> {
            to(Web1Activity.class);
        });
    }

    private void ams() {
        to(TestActivity.class);
    }

    private void gif() {
        if (mPlayer == null) {
            mPlayer = new GifPlayer(this);
            mPlayer.assetPlay(this, "mao.gif");
            mPlayer.setOnGifListener(new GifPlayer.OnGifListener() {
                @Override
                public void start() {
                    P.d(T, "start");
                }

                @Override
                public void draw(Bitmap bitmap) {
                    P.d(T, "draw");
                    mBinding.ivBlur.setImageBitmap(bitmap);
                }

                @Override
                public void end() {
                    P.d(T, "end");
                }
            });
        }
    }

    private void md5() {


        MD5.signVerify(this);

        String str = "123";
        toast(MD5.toMD5(str, "22", 0));
    }

    private void blur() {
        MethodJni jni = new MethodJni();
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ma);
        jni.handleBlur(bitmap);
        mBinding.ivBlur.setImageBitmap(bitmap);
    }

    private void prototype() {
        Message message = new Message();
        message.setName("张三");
        message.setDetail(100.0);


        Message m1 = message.clone();
        m1.setName("李四");
        m1.setDetail(200.0);

        Message m2 = message.clone();
        m2.setName("王五");
        m2.setDetail(300.0);

        message.send();
        m1.send();
        m2.send();
    }

    private void jni() {
        // String msg = JniUtil.getMsg();
        //String msg = JniUtil.getConcatStr();
        //int msg = JniUtil.equalJni("我是我", "我是我");

        /*int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        int sum = JniUtil.arraySum(arr);*/
        //String sum = JniUtil.testJni();
        /*MethodJni jni = new MethodJni();
        toast("动态注册方法  = " + jni.getStringFromCpp());*/

        int[] arr = {3, 2, 5, 6, 9, 8, 7, 4, 1};


        P.d("---------数组未排序---------");

        printArr(arr);
        mJni = new MethodJni();
        int[] jniArr = mJni.jniArr(arr, arr.length);
        P.d("---------数组排序后---------");
        printArr(jniArr);
    }


    private void printArr(int[] arr) {
        for (int j : arr)
            P.d("数组 : " + j);
    }

    private void numberTest() {

    }

    private void decorator2() {
        BigCake cake = new BigCake(new CreamCake(new CandleCake(new Cake())));
        toast(cake.des());
    }

    public void shareNetImage(Activity context, String url) {
        Glide.with(context).asBitmap().load(url).into(new SimpleTarget<Bitmap>(SIZE_ORIGINAL, SIZE_ORIGINAL) {
            @Override
            public void onResourceReady(@NonNull Bitmap bitmap, @Nullable Transition<? super Bitmap> transition) {
                //由文件得到uri
                Uri imageUri = Uri.parse(MediaStore.Images.Media.insertImage(context.getContentResolver(), bitmap, null, null));
                Intent shareIntent = new Intent();
                shareIntent.setAction(Intent.ACTION_SEND);
                shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
                shareIntent.setType("image/*");
                context.startActivity(Intent.createChooser(shareIntent, "分享到"));
            }
        });
    }

    private void decorator() {
        RedHair hunter = new RedHair(new WhitePants(new WhiteJacket(new Hunter())));
        toast(hunter.des());

    }

    private void night() {
        NightManager.Companion.get().setSystemMode(false);
        NightManager.Companion.get().setNightMode(false);
        ThreadUtil.runOnUiThread(() -> {
            NightManager.Companion.get().initNightMode();
            NightManager.Companion.get().restartApp(MainActivity.this);
        }, 500);
    }

    @SuppressLint("CheckResult")
    private void rxBus() {
        Disposable disposable = RxBus.Companion.get().to(11, String.class)
                .subscribe(this::toast);
    }

    private void strategy2() {
        MovieTicket ticket = new MovieTicket();
        ticket.setPrice(60.0);
        System.out.println("原始价格为: " + 60.0);
        System.out.println("--------------------");

        ticket.setDiscount((Discount) XmlUtil.Companion.get().getClass());

        System.out.println("打完折价格为: " + ticket.getPrice());
    }

    private void strategy() {
        AirStrategy airStrategy = new AirStrategy();
        PersonStrategy personStrategy = new PersonStrategy();
        TripContext tripContext = new TripContext(personStrategy);
        tripContext.tripType();
    }

    private void observer() {
        DingServer<String> server = new DingServer<>();
        User u1 = new User("小明");
        User u2 = new User("小红");
        User u3 = new User("小王");

        server.register(u1);
        server.register(u2);
        server.register(u3);

        server.issue("玩了一把消消乐");

        server.remove(u2);
        server.issue("又玩了一把消消乐");
    }

    private void chain() {
        OneCheck oneCheck = new OneCheck();
        TwoCheck twoCheck = new TwoCheck();
        ThreeCheck threeCheck = new ThreeCheck();
        oneCheck.setNext(twoCheck);
        twoCheck.setNext(threeCheck);
        oneCheck.execute();
    }

    private void single() {
        //String string = SimpleSingleton.Companion.get(this).getString();
        /*String string = SimpleSingle.Companion.get().getString();
        P.e("single", string);*/
        //SimpleSingle.Companion.get().execute();
        String s = TestSingle.Companion.get().testSingle();
        P.e("single", s);
    }


    private void executeProxy() {
        /*StudyInterface school = new RealSchool();
        RealHandler handler = new RealHandler(school);
        StudyInterface proxyInstance = (StudyInterface) Proxy.newProxyInstance(
                school.getClass().getClassLoader(),
                school.getClass().getInterfaces(),
                handler);

        proxyInstance.study();*/

        /*TwoInterface two = ProxyFactory.create(TwoInterface.class, Two.class);
        two.two();*/

        ApiBookInterface api = new TestRetrofit.Builder()
                .build().create(ApiBookInterface.class);
        api.getBook().read();
    }


    private void exchange() {
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);
        Node node4 = new Node(4);
        node1.setMNext(node2);
        node2.setMNext(node3);
        node3.setMNext(node4);

        Test test = new Test();
        test.swapPairs(node1);
    }

    private void setDrawable() {
        //mBinding.downLoad.setBackground(Shape.gradient(25f, R.color.startColor, R.color.endColor, R.color.centerColor));
        //mBinding.downLoad.setBackground(Shape.stroke( R.color.startColor, 2));
        /*mBinding.downLoad.setBackground(Shape.stroke(25f, R.color.startColor, 2));
        mBinding.version.setBackground(Shape.sp(R.color.Green, 15));*/
    }


    @Permission(value = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE})
    public void merge() {
        /*FileLoader loader = new FileLoader(this);
        File file = loader.loadInBackground();
        assert file != null;
        ApkUtils.installApk(file, MainActivity.this);*/

        ThreadUtil.getThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                String oldApk = getApplicationInfo().sourceDir;
                final String newApk = createNewApk().getAbsolutePath();
                String patch = new File(getExternalFilesDir(null), "new.patch").getAbsolutePath();
                //int result = PatchUtil.patchUpdate(oldApk, newApk, patch);

                /*if (result == 1) {
                    P.d("文件合并完成");
                }*/
                ThreadUtil.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ApkUtils.installApk(new File(newApk), MainActivity.this);
                        //InstallUtils.installApk(MainActivity.this, new File(newApk));
                    }
                }, 3000);
            }
        });

    }

    private File createNewApk() {
        File newApk = new File(getExternalFilesDir(null), "bspatch.apk");
        try {
            if (!newApk.exists()) {
                boolean isCreated = newApk.createNewFile();
                if (isCreated) P.d("文件创建成功");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return newApk;
    }


    @Permission(value = {Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE})
    private void down() {
        if (mDialog == null)
            mDialog = new ProgressDialog();
        mViewModel.download();
        if (mDialog != null) mDialog.show(getSupportFragmentManager(), "down");

        mViewModel.updateStatus().observe(this, fileInfo -> ThreadUtil.runOnUiThread(() -> {
            mDialog.setNumberBar(fileInfo.getCalculateProgress());
            mDialog.setTitle(fileInfo.getCalculateDown(), fileInfo.getCalculateTotal());
            P.d(fileInfo.getDownloadLocation() + "   <-");
            if (fileInfo.getDownloadStatus() == DownloadStatus.COMPLETE) {
                toast("下载完成了");
                mDialog.setTitle("下载完成了", "");
                mDialog.dismiss();
            }
        }));
    }

    private void updateBanners(List<BannerBean> data) {
        if (data == null || data.size() <= 0) {
            return;
        }
        mUrls = new ArrayList<>();
        mTitles = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            mUrls.add(data.get(i).getImagePath());
            mTitles.add(data.get(i).getTitle());
        }
        mUrls.add(data.get(1).getImagePath());
        mTitles.add(data.get(1).getTitle());
        mBinding.mBanner.setBannerTitles(mTitles);
        mBinding.mBanner.setImages(mUrls);
        mBinding.mBanner.start();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.mBanner) {
            toast("点击了 banner");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mJni != null)
            mJni.recycle();
    }

    @Override
    public void onDenied(List<String> permissions) {
        toast("权限被拒绝" + permissions.get(0));
    }

    @Intercept(222)
    private void checkClick() {
        toast("点击过了_执行了");
    }


    private void log() {
        if (readProp("log") == 1)
            P.i("打出了LOG");
    }


    private int readProp(String prop) {
        try {
            Process process = Runtime.getRuntime().exec("getprop " + prop);
            InputStreamReader ir = new InputStreamReader(process.getInputStream());
            BufferedReader input = new BufferedReader(ir);
            String line = input.readLine();
            if (TextUtils.isEmpty(line))
                return 0;
            return Integer.parseInt(input.readLine());
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
}